<?php

	header("Cache-Control: no-cache, must-revalidate");

	session_start();

	require_once ("view/HTMLPageView.php");
	require_once ("view/HTMLloginView.php");
	require_once ("random_string.php");

	$pageView = new \view\HTMLPageView();
	$loginPageView = new \view\HTMLloginView();

	$correctName = "Admin";
	$correctPassW = "123";

	/**
	 * If user is logged in with cookie
	 */
	if (isset($_COOKIE["Name"]) && isset($_COOKIE["Password"]))
	{
		/**
		 * TODO - Validate cookies
		 */
		echo $loginPageView->getLoginPage
		("Du är inloggad med hjälp av kakor som ", $_COOKIE["Name"], "Inloggad");
	}

	/**
	 * If user is logged in with session
	 */
	else if (isset($_SESSION["session_password"]))
	{
		echo $loginPageView->getLoginPage
		("Du är inloggad via sessionen ", $_SESSION["session_name"], "Inloggad");
	}

	/**
	 * If form is filled in at logg in attempt
	 * TODO - Fix inputvalidation
	 */
	else if (isset($_POST["Name"]) || ($_POST["Password"]))
	{
		$userName = $_POST["Name"];
		$userPassW = $_POST["Password"];

		//If values are correct
		if ($userName == $correctName && $userPassW == $correctPassW)
		{
			//If user chooses to stay logged in (Checked box)
			if (isset($_POST["CheckBox"]) && $_POST["CheckBox"] == 'yes')
			{
				$myRandomPassword = new random_string();
				$cookiePassword = $myRandomPassword->createRandomString();

				setcookie("Name", $userName, time() + 3600);
				setcookie("Password", $cookiePassword, time() + 3600);

				echo $loginPageView->getLoginPage
				("Hej och Välkommen. ", "Vi kommer ihåg dig " . $userName, "Inloggad");
			}

			$_SESSION["session_name"] = $userName;
			$_SESSION["session_password"] = $userPassW;

			echo $loginPageView->getLoginPage
			("Hej och Välkommen. ", "Du är inloggad som " . $userName, "Inloggad");
		}
		else if ($userName == $correctName && $userPassW != $correctPassW)
		{
			echo $pageView->getPage
			("Fel lösenord och/eller användarnamn.", "Ej Inloggad", $userName);
		}
		else if ($userName != $correctName && $userPassW == $correctPassW)
		{
			echo $pageView->getPage
			("Fel användarnamn och/eller lösenord.", "Ej Inloggad", $userName);
		}
		else
		{
			echo $pageView->getPage
			("Fel användaruppgifter. Försök igen!", "Ej Inloggad", null);
		}
	}
	else
	{
		header("Location: labb1.php");
	}
